package lc.q101_150;

import lc.TreeNode;

import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;

public class Q101 {
    public boolean isSymmetric(TreeNode root) {
        return root == null || isSymmetric(root.left, root.right);
    }

    // 递归的方式
    private boolean isSymmetric(TreeNode left, TreeNode right) {
        if (left == null) {
            return right == null;
        }
        if (right == null) {
            return false;
        }
        return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left);
    }

    // 迭代的方式
    private boolean isSymmetric2(TreeNode left, TreeNode right) {
        // 通过将根存进栈中
        Queue<TreeNode> queue = new LinkedBlockingQueue<>();
        queue.offer(left);
        queue.offer(right);
        while (!queue.isEmpty()) {
            final TreeNode l = queue.poll();
            final TreeNode r = queue.poll();
            if (l == null && r == null) continue;
            if ((l == null || r == null) || (l.val != r.val)) return false;
            queue.offer(l.left);
            queue.offer(r.right);
            queue.offer(l.right);
            queue.offer(r.left);
        }
        return true;
    }

}
